package com.huacai.framework.interceptor;

import com.huacai.common.exception.DemoEnvironmentException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 演示环境拦截器
 */
@Component
public class DemoEnvironmentInterceptor implements HandlerInterceptor {

    // 从配置文件中读取是否启用演示环境
    @Value("${demo.env.enabled:false}")
    private boolean isDemoEnvironment;

    // 需要排除的URL，比如登录、注销等
    private static final String[] EXCLUDE_URLS = {
            "/login",
            "/logout",
            "/captchaImage"
    };

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 如果不是演示环境，直接放行
        if (!isDemoEnvironment) {
            return true;
        }

        // 获取请求URI
        String requestURI = request.getRequestURI();

        // 检查是否在排除列表中
        for (String excludeUrl : EXCLUDE_URLS) {
            if (requestURI.contains(excludeUrl)) {
                return true;
            }
        }

        // 拦截所有非GET请求
        String method = request.getMethod();
        if (!"GET".equalsIgnoreCase(method)) {
            throw new DemoEnvironmentException("演示环境，不允许进行此操作");
        }

        return true;
    }
}
